App.MainApp.module('containerModule', function(containerModule){
	_container = null;

	// Models for Container
	var PagesModel  = Backbone.Collection.extend({ model: PageModel });
	var PageModel   = Backbone.Model.extend({ });
	var HeaderModel = Backbone.Model.extend({ });

	// Views for Container
	var PageView = Marionette.ItemView.extend({ tagName: "div" })	
	var TabView = Marionette.ItemView.extend({
		tagName: "li",
		template: "#container-layout-template-tab"	
	});
	var HeaderView = Marionette.CompositeView.extend({
		tagName: 'div',
		itemView: TabView,
		appendHtml: function(collectionView, itemView, index){
			var Page = new PageView({ id: itemView.model.attributes.name })
			collectionView.$("#" +  this.id  +"-tabs").append(itemView.el);
			collectionView.$el.append(Page.el);
		},
		onRender: function() {
			if (App.debug) console.log('App.containerModule HeaderView render completed');
		}
	});
   this.startWithParent = false;

	// Controller for Container
	var Controller = Marionette.Controller.extend({
		initialize: function(options){
			if (App.debug) console.log('App.containerModule Controller initialized');
			self = this;
			this.Pages = new PagesModel;
			this.region = options.region;
			_.each(options.items, function(item) {
				var Page = new PageModel({name: item.name});
				self.Pages.add(Page);
			});
		},
		show: function(options) {
			if (App.debug) console.log('App.containerModule Controller show invoked');
			header_view = new HeaderView({
				id: options.id,
				template: '#' + options.template,
				collection: this.Pages,
				model: new HeaderModel({name: options.id}),
			});
			options.region.show(header_view);
		},
		render: function(options) {
			if (App.debug) console.log('App.containerModule Controller render invoked');
			_container = $('#' + options.id).wijtabs({
            sortable: true
         });
		},
		change_tab: function(index) {
			if (App.debug) console.log('App.containerModule Controller change_tab invoked');
			if (App.debug) console.log('App.containerModule Controller change_tab index:' + index);
			_container.wijtabs('select', index);
		}
	});
	
	containerModule.addInitializer(function (options) {
		if (App.debug) console.log('App.containerModule addInitializer');
		var defaults = {
			region: App.MainApp.containerRegion,
			items:  [{name: 'page1'}]
		};
		options = _.extend(defaults, options);
		containerModule.Controller = new Controller({
			region: options.region,
			items: options.items
		});
		containerModule.Controller.show(options);
		containerModule.Controller.render(options);
   });
});

App.MainApp.containerModule.on("before:start", function(){
	if (App.debug) console.log('App.containerModule before:start');
});
App.MainApp.containerModule.on("start", function(){
	if (App.debug) console.log('App.containerModule start');
});

